package cn.xshi.common.base;

import java.util.*;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import cn.xshi.common.cache.redis.RedisUtil;
import cn.xshi.common.entity.*;
import cn.xshi.common.form.UserForm;
import cn.xshi.common.idgeneration.UUID;
import cn.xshi.common.util.ExceptionUtil;
import cn.xshi.common.util.JsonUtil;
import cn.xshi.common.util.RestTemplateUtil;
import cn.xshi.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
 * @Desc 公用类获取平台信息方法如获取登录用户信息,当前用户部门,当前用户岗位等一系列信息
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
@Slf4j
@Primary
public class BaseUtils extends UUID {

	@Resource
    RestTemplateUtil restTemplateUtil;

	@Resource
    RedisUtil redisUtil;

	/**
	 * 当前登录者姓名
	 * @return
	 */
	public String getCurrentName() {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseResult baseResult = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/uName",BaseResult.class,request);
			if(null == baseResult){
				return null;
			}
			return ""+baseResult;
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 当前账号
	 * @return
	 */
	public String getCurrentAccount() {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseResult baseResult = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/account",BaseResult.class,request);
			if(null == baseResult){
				return null;
			}
			return ""+baseResult.getData();
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 查询当前账号id编号
	 * @return
	 */
	public String getCurrentAccountId() {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseResult baseResult = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/accountId",BaseResult.class,request);
			if(null == baseResult){
				return null;
			}
			return ""+baseResult.getData();
		} catch (Exception e) {
			log.error("获取系统用户id出现异常：{0}",e);
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 当前账号所在部门编号
	 * @return
	 */
	public String getCurrentDepartId() {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseHttpSessionEntity baseHttpSessionEntity = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/httpSessionEntity",BaseHttpSessionEntity.class,request);
			if(null == baseHttpSessionEntity || null == baseHttpSessionEntity.getUserInfoEntity()){
				return null;
			}
			return baseHttpSessionEntity.getUserInfoEntity().getDepartInfoId();
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 获取当前用户对象信息
	 *
	 * @return
	 */
	public BaseHttpSessionEntity getBaseHttpSessionEntity() {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseHttpSessionEntity baseHttpSessionEntity = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/httpSessionEntity",BaseHttpSessionEntity.class,request);
			return baseHttpSessionEntity;
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 当前登录者信息
	 * @return
	 */
	public OauthAccountEntity getCurrentAccountInfo() {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			OauthAccountEntity oauthAccountEntity = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/accountInfo",OauthAccountEntity.class,request);
			return oauthAccountEntity;
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}


	/**
	 * 获取数据权限
	 * @return
	 */
	public List<String> systemUandM(){
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			List<String> list = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/systemUandM",List.class,request);
			return list;
		} catch (Exception e) {
			throw new ExceptionUtil("获取systemUandM出现异常："+e.getMessage());
		}
	}

	/**
	 * 判断当前用户是否为超级管理员
	 *
	 * @return
	 */
	public boolean isAdmin() {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			Boolean aBoolean = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/isAdmin",Boolean.class,request);
			return aBoolean;
		} catch (Exception e) {
			throw new ExceptionUtil("获取systemUandM出现异常："+e.getMessage());
		}
	}

	/**
	 * 获取缓存值
	 *
	 * @return
	 */
	public static Object getCache(String key) {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
		ServletContext sc = request.getSession(false).getServletContext();
//		Map<String, Object> map = (Map<String, Object>) sc.getAttribute("sys_message");
//		return map.get(key);
		return (String)sc.getAttribute(key);
	}

	/**
	 * 获取缓存值
	 *
	 * @return
	 */
	public static String getCacheStr(String key) {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
		ServletContext sc = request.getSession().getServletContext();
//		Map<String, Object> map = (Map<String, Object>) sc.getAttribute("sys_message");
//		return (String) map.get(key);
		return (String)sc.getAttribute(key);
	}

	/**
	 * 根据KEY获取平台路径
	 * @param key
	 * @return
	 */
	public List<PathEntity> getSysPathCache(String key) {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseResult baseResult= restTemplateUtil.get(restTemplateUtil.restSysURL() + "/sysCommon/path/list?key="+key,BaseResult.class,request);
			List<PathEntity> list = JsonUtil.toList(""+baseResult.getData(),PathEntity.class);
			return list;
		} catch (Exception e) {
			throw new ExceptionUtil("获取PathEntity出现异常："+e.getMessage());
		}
	}

	/**
	 * 统一验证错误 通过注解捕捉字段验证错误信息
	 * @param bindingResult
	 * @return
	 */
	public String backFem(BindingResult bindingResult){
		List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < fieldErrorList.size(); i++) {
			FieldError fieldError =fieldErrorList.get(i);
			sb.append("错误字段消息："+fieldError.getField() +" : "+fieldError.getDefaultMessage()+"<br>");
		}
		return sb.toString();
	}

	/**
	 * 判断当前请求是否异步
	 * @param request
	 * @return
	 */
	public static boolean isAjaxReq(HttpServletRequest request){
		String head = request.getHeader("x-requested-with");
		//XMLHttpRequest为异步 Ext.basex为同步 则Ajax拦截
		if((null != head && (head.equalsIgnoreCase("XMLHttpRequest")|| "Ext.basex".equalsIgnoreCase(head)))) {
			return true;
		}
		return false;
	}

	/**
	 * 根据KEY获取平台字典
	 * @param key
	 * @return
	 */
	public List<DataDictionaryEntity> getSysDataDictionaryCache(String key) {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			List<DataDictionaryEntity> dataDictionaryEntities = restTemplateUtil.get(restTemplateUtil.restSysURL() + "/sysCommon/dataDictionary/list/"+key,List.class,request);
			return dataDictionaryEntities;
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 根据父KEY+子Key获取平台字典
	 * @param parentKey
	 * @param subKey
	 * @return
	 */
	public DataDictionaryEntity getSysDataDictionaryFromCache(String parentKey,String subKey) {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			DataDictionaryEntity dataDictionaryEntity = restTemplateUtil.get(restTemplateUtil.restSysURL() + "/sysCommon/dataDictionary/list/"+parentKey+"/"+subKey,DataDictionaryEntity.class,request);
			return dataDictionaryEntity;
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 判断IP是否为黑户
	 * @param ip
	 * @return
	 */
	public boolean getSysIpFrozenCache(String ip){
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			Boolean baseResult = restTemplateUtil.get(restTemplateUtil.restSysURL() + "/sysCommon/ipFrozen/validate/"+ip,Boolean.class,request);
			return baseResult;
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 获取公共功能缓存
	 * @return
	 */
	public String getSysFunctionInfoCommonCache(){
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			String baseResult = restTemplateUtil.get(restTemplateUtil.restSysURL() + "/sysCommon/functionInfoCommon/list",String.class,request);
			if(null == baseResult){
				return null;
			}
			return ""+baseResult;
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 随机生成唯一client.id方法
	 * @return
	 */
	public static String getClientId(){
		String nums = "";
		String[] codeChars = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
				"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
				"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
		for (int i = 0; i < 23; i++)
		{
			int charNum = (int)Math.floor(Math.random() * codeChars.length);
			nums = nums + codeChars[charNum];
		}
		return nums;
	}

	/**
	 * 获取账户更多信息
	 * @param userParamInfo
	 * @return
	 */
	public UserParamInfo infoList(UserParamInfo userParamInfo) {
		try {
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseResult baseResult= restTemplateUtil.post(restTemplateUtil.restOauthURL() + "/oauthAccount/infoList",BaseResult.class,userParamInfo,request);
			userParamInfo =JsonUtil.fromAliFastJson(""+baseResult.getData(),UserParamInfo.class);
			return userParamInfo;
		} catch (Exception e) {
			throw new ExceptionUtil("获取UserParamInfo出现异常："+e.getMessage());
		}
	}

	/**
	 * 根据账号id查找账户信息
	 * @param accountId
	 * @return
	 */
	public OauthAccountEntity getAccount(String accountId) {
		try {
			if(StringUtil.isEmpty(accountId)){
				return null;
			}
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseResult baseResult = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/oauthAccount/get/"+accountId,BaseResult.class,request);
			if(null == baseResult){
				return null;
			}
			OauthAccountEntity oauthAccount = JsonUtil.fromFastJson(baseResult.getData(),OauthAccountEntity.class);
			return oauthAccount;
		} catch (Exception e) {
			log.error("获取账户异常：{0}",e);
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 根据 Token查找在线用户
	 * @param token
	 * @return
	 */
	public OauthAccountEntity getOnlineAccount(String token) {
		try {
			if(StringUtil.isEmpty(token)){
				return null;
			}
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseHttpSessionEntity baseHttpSessionEntity = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/oauthAccount/tokenInfoByToken?token="+token,BaseHttpSessionEntity.class,request);
			if(null == baseHttpSessionEntity){
				return null;
			}
			return baseHttpSessionEntity.getOauthAccountEntity();
		} catch (Exception e) {
			log.error("获取在线账户异常：{0}",e);
			return null;
		}
	}

	/**
	 * 根据 Token查找在线用户
	 * @param token
	 * @return
	 */
	public OauthAccountEntity getOnlineAccount(String token,HttpServletRequest request) {
		try {
			if(StringUtil.isEmpty(token)){
				return null;
			}
			BaseHttpSessionEntity baseHttpSessionEntity = restTemplateUtil.get(restTemplateUtil.restOauthURL() + "/oauthAccount/tokenInfoByToken?token="+token,BaseHttpSessionEntity.class,request);
			if(null == baseHttpSessionEntity){
				return null;
			}
			return baseHttpSessionEntity.getOauthAccountEntity();
		} catch (Exception e) {
			log.error("获取在线账户异常：{0}",e);
			return null;
		}
	}

	/**
	 * 根据 Token查找在线用户
	 * @param token
	 * @return
	 */
	public OauthAccountEntity getOnlineAccount(String token,HttpHeaders headers) {
		try {
			if(StringUtil.isEmpty(token)){
				return null;
			}
			BaseHttpSessionEntity baseHttpSessionEntity = restTemplateUtil.getUnRequest(restTemplateUtil.restOauthURL() + "/tokenInfoByToken?token="+token,BaseHttpSessionEntity.class,headers);
			if(null == baseHttpSessionEntity){
				return null;
			}
			return baseHttpSessionEntity.getOauthAccountEntity();
		} catch (Exception e) {
			log.error("获取在线账户异常：{0}",e);
			return null;
		}
	}

	/**
	 * 根据 accountId查找在线用户Token
	 * @param accountId
	 * @return
	 */
	public BaseResult getOnlineAccountToken(String accountId,HttpHeaders headers) {
		try {
			if(StringUtil.isEmpty(accountId)){
				return null;
			}
			BaseResult baseResult = restTemplateUtil.getUnRequest(restTemplateUtil.restOauthURL() + "/tokenByAccountId?accountId="+accountId,BaseResult.class,headers);
			return baseResult;
		} catch (Exception e) {
			log.error("获取在线账户Token异常：{0}",e);
			return null;
		}
	}

	/**
	 * 查询行政区域单条记录
	 * @param id
	 * @return
	 */
	public AreaRegionEntity getAreaRegionEntity(String id){
		try {
			if(StringUtil.isEmpty(id)){
				return null;
			}
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			BaseResult baseResult = restTemplateUtil.get(restTemplateUtil.restSysURL() + "/sysAreaRegion/get/"+id,BaseResult.class,request);
			if(null == baseResult){
				return null;
			}
			return JsonUtil.fromFastJson(baseResult.getData(),AreaRegionEntity.class);
		} catch (Exception e) {
			log.error("查询行政区域单条记录出现异常：{0}",e);
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 根据条件查找用户集合（包含部门编号逗号分隔，岗位编号逗号分隔，用户编号逗号分隔）
	 * @param userForm
	 * @return
	 */
	public List<UserInfoEntity> getUserInfoEntityList(UserForm userForm){
		List<UserInfoEntity> userInfoEntities = null;
		try {
			BaseResult<List<UserInfoEntity>> baseResult = restTemplateUtil.post(restTemplateUtil.restSysURL() + "/xtUserinfo/getUserinfoList",BaseResult.class,userForm);
			if(null == baseResult){
				return userInfoEntities;
			}
			userInfoEntities = JsonUtil.toFastList(baseResult.getData(),UserInfoEntity.class);
			return userInfoEntities;
		} catch (Exception e) {
			log.error("查找用户集合出现异常：{0}",e);
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 * 创建站内通知
	 * @param baseNotifyEntity
	 * @return
	 */
	public int createNotify(BaseNotifyEntity baseNotifyEntity){
		try {
			BaseResult baseResult = restTemplateUtil.post(restTemplateUtil.restSysURL() + "/xtNotify/createNotify",BaseResult.class,baseNotifyEntity);
			if(null == baseResult){
				return -1;
			}
			return 1;
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}
}
